<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AI对话系统</title>
    <!--<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>-->
    <style>
        * {
            box-sizing: border-box;
            margin: 0;
            padding: 0;
            font-family: 'Arial', sans-serif;
        }

        body {
            background-color: #f5f7fa;
            color: #333;
            line-height: 1.6;
        }

        .message {
            margin-bottom: 12px;
            padding: 10px 15px;
            border-radius: 8px;
            max-width: 80%;
            word-wrap: break-word;
        }
        .message.user {
            background-color: #e3f2fd;
            margin-left: auto;
            border-bottom-right-radius: 4px;
        }

        .message.assistant {
            background-color: #ffffff;
            margin-right: auto;
            border-bottom-left-radius: 4px;
            box-shadow: 0 1px 2px rgba(0,0,0,0.1);
        }

        .message-time {
            font-size: 12px;
            color: #666;
            margin-top: 5px;
            text-align: right;
        }
        /* 添加页面切换动画 */
        .page {
          transition: opacity 0.3s ease;
        }

        .page.hidden {
          display: none;
          opacity: 0;
        }

        /* 激活按钮样式 */
        .nav-btn.active {
          background: #4a90e2 !important;
          color: white !important;
          box-shadow: 0 2px 6px rgba(0,0,0,0.2);
          position: relative;
        }

        .nav-btn.active::after {
          content: "";
          position: absolute;
          bottom: -13px;
          left: 50%;
          transform: translateX(-50%);
          width: 80%;
          height: 3px;
          background: #4a90e2;
          border-radius: 2px;
        }

        /* IoT 按钮激活状态特殊处理 */
        .nav-btn.iot-btn.active {
          background: #00c853 !important;
        }

        /* 在您的CSS文件中添加 */
        .iot-route-btn {
            padding: 10px 15px;
            background-color: #4CAF50;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
            margin-bottom: 20px;
        }

.iot-route-btn:hover {
    background-color: #45a049;
}


        .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
            display: flex;
            min-height: 100vh;
        }

        /* 侧边栏样式 */
        .sidebar {
            width: 250px;
            background-color: #2c3e50;
            color: white;
            padding: 20px;
            border-radius: 10px 0 0 10px;
            display: flex;
            flex-direction: column;
        }

        .brand {
            font-size: 1.5rem;
            margin-bottom: 30px;
            text-align: center;
            padding-bottom: 15px;
            border-bottom: 1px solid #3d5166;
        }

        .user-info {
            display: flex;
            align-items: center;
            margin-bottom: 20px;
            padding: 10px;
            background-color: #34495e;
            border-radius: 5px;
        }

        .user-avatar {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background-color: #3498db;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-right: 10px;
            font-weight: bold;
        }

        .nav-menu {
            flex-grow: 1;
        }

        .nav-item {
            padding: 12px 15px;
            margin-bottom: 5px;
            border-radius: 5px;
            cursor: pointer;
            transition: background-color 0.3s;
        }

        .nav-item:hover, .nav-item.active {
            background-color: #34495e;
        }

        .logout-btn {
            background-color: #e74c3c;
            color: white;
            border: none;
            padding: 10px;
            border-radius: 5px;
            cursor: pointer;
            margin-top: auto;
            width: 100%;
        }

        /* 主内容区样式 */
        .main-content {
            flex-grow: 1;
            background-color: white;
            border-radius: 0 10px 10px 0;
            padding: 20px;
            display: flex;
            flex-direction: column;
        }

        /* 登录/注册表单样式 */
        .auth-container {
            max-width: 400px;
            margin: 50px auto;
            padding: 30px;
            background-color: white;
            border-radius: 10px;
            box-shadow: 0 0 20px rgba(0, 0, 0, 0.1);
        }

        .auth-title {
            text-align: center;
            margin-bottom: 20px;
            color: #2c3e50;
        }

        .auth-form .form-group {
            margin-bottom: 20px;
        }

        .auth-form label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
        }

        .auth-form input {
            width: 100%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 5px;
            font-size: 16px;
        }

        .auth-form button {
            width: 100%;
            padding: 12px;
            background-color: #3498db;
            color: white;
            border: none;
            border-radius: 5px;
            font-size: 16px;
            cursor: pointer;
            transition: background-color 0.3s;
        }

        .auth-form button:hover {
            background-color: #2980b9;
        }

        .auth-switch {
            text-align: center;
            margin-top: 20px;
        }

        .auth-switch a {
            color: #3498db;
            text-decoration: none;
            cursor: pointer;
        }

        /* 对话界面样式 */
        .chat-container {
            display: flex;
            flex-direction: column;
            height: 100vh; /* 或固定高度 */
            padding: 20px;
            box-sizing: border-box;
        }

        .chat-messages {
            background-color: #f5f5f5;
            padding: 15px;
            border-radius: 8px;
            height: 400px;
            overflow-y: auto;
            margin-bottom: 15px;
        }

        .chat-input {
            padding: 10px 0;
            position: sticky;
            bottom: 0;
            background: white;
        }


        .chat-header {
            padding: 15px;
            border-bottom: 1px solid #eee;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .chat-input input {
            flex-grow: 1;
            padding: 12px;
            border: 1px solid #ddd;
            border-radius: 5px;
            margin-right: 10px;
        }

        .chat-input button {
            padding: 12px 20px;
            background-color: #3498db;
            color: white;
            border: none;
            border-radius: 5px;
            cursor: pointer;
        }

        /* 角色管理样式 */
        .role-management {
            padding: 20px;
        }

        .role-list {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
            gap: 20px;
            margin-top: 20px;
        }

        .role-card {
            background-color: #f9f9f9;
            border-radius: 8px;
            padding: 15px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
        }

        .role-card h3 {
            margin-bottom: 10px;
            color: #2c3e50;
        }

        .role-card p {
            color: #666;
            margin-bottom: 15px;
        }

        .role-actions {
            display: flex;
            justify-content: space-between;
        }

        .role-actions button {
            padding: 5px 10px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }

        .edit-btn {
            background-color: #3498db;
            color: white;
        }

        .delete-btn {
            background-color: #e74c3c;
            color: white;
        }

        .add-role-btn {
            background-color: #2ecc71;
            color: white;
            padding: 10px 15px;
            border: none;
            border-radius: 5px;
            margin-bottom: 20px;
            cursor: pointer;
        }

        /* 设置页面样式 */
        .settings-container {
            padding: 20px;
        }

        .settings-form {
            max-width: 500px;
        }

        .settings-form .form-group {
            margin-bottom: 20px;
        }

        .settings-form label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
        }

        .settings-form input, .settings-form select {
            width: 100%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 5px;
        }

        .settings-form button {
            background-color: #3498db;
            color: white;
            padding: 10px 15px;
            border: none;
            border-radius: 5px;
            cursor: pointer;
        }

        /* 响应式设计 */
        @media (max-width: 768px) {
            .container {
                flex-direction: column;
            }

            .sidebar {
                width: 100%;
                border-radius: 10px 10px 0 0;
                margin-bottom: 20px;
            }

            .main-content {
                border-radius: 0 0 10px 10px;
            }
        }

        /* 隐藏类 */
        .hidden {
            display: none !important;
        }
        /* 导航控制栏样式 */
        .global-controls {
            display: flex;
            gap: 12px;
            padding: 16px;
            background: #f5f7fa;
            border-bottom: 1px solid #e4e7ed;
            margin-bottom: 20px;
        }

        .nav-btn {
            padding: 8px 16px;
            background: white;
            border: 1px solid #e4e7ed;
            border-radius: 6px;
            cursor: pointer;
            display: flex;
            align-items: center;
            gap: 6px;
            transition: all 0.2s;
        }

        .nav-btn:hover {
            background: #4a90e2;
            color: white;
            border-color: #4a90e2;
            transform: translateY(-2px);
        }

        .nav-btn.iot-btn {
            background: #00c853;
            color: white;
            border-color: #00c853;
        }

        .nav-btn.iot-btn:hover {
            background: #009624;
        }

        .icon {
            width: 18px;
            height: 18px;
            fill: currentColor;
        }

                /* 添加到您的样式表中 */
        .dropdown {
            position: relative;
            z-index: 1000;
        }

        .dropdown-toggle {
            cursor: pointer;
            display: flex;
            align-items: center;
            gap: 6px;
        }

        .dropdown-arrow {
            font-size: 10px;
            margin-left: 4px;
            transition: transform 0.2s;
        }

        .dropdown:hover .dropdown-arrow {
            transform: rotate(180deg);
        }

        .dropdown-menu {
            position: absolute;
            right: 0;
            z-index: 1000;
            display: none;
            min-width: 180px;
            padding: 8px 0;
            margin: 2px 0 0;
            font-size: 14px;
            color: #333;
            background-color: #fff;
            border: 1px solid rgba(0,0,0,.15);
            border-radius: 6px;
            box-shadow: 0 6px 12px rgba(0,0,0,.175);
        }

        .dropdown:hover .dropdown-menu {
            display: block;
        }

        .dropdown-item {
            display: flex;
            align-items: center;
            padding: 8px 16px;
            color: #333;
            text-decoration: none;
            transition: all 0.2s;
        }

        .dropdown-item:hover {
            background-color: #f5f5f5;
            color: #1890ff;
        }

        .icon-text {
            margin-right: 10px;
            width: 20px;
            text-align: center;
        }

        .dropdown-divider {
            height: 1px;
            margin: 8px 0;
            overflow: hidden;
            background-color: #e8e8e8;
        }

        .iot-btn {
            position: relative;
        }

        /* 小屏幕适配 */
        @media (max-width: 768px) {
            .dropdown-menu {
                position: static;
                width: 100%;
            }
        }
        /* 添加到您的样式表中 */
        .file-upload-container {
            display: flex;
            align-items: center;
            margin-bottom: 8px;
        }

        .file-upload-btn {
            display: flex;
            align-items: center;
            padding: 6px 12px;
            background-color: #f0f0f0;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
            transition: background-color 0.2s;
        }

        .file-upload-btn:hover {
            background-color: #e0e0e0;
        }

        .file-upload-btn svg {
            margin-right: 6px;
            fill: #555;
        }

        .file-name {
            margin-left: 10px;
            font-size: 14px;
            color: #666;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            max-width: 200px;
        }

        .file-message {
            background-color: #f5f5f5;
            border-radius: 8px;
            padding: 10px;
            margin: 8px 0;
            display: inline-block;
        }

        .file-message a {
            color: #1890ff;
            text-decoration: none;
            display: flex;
            align-items: center;
        }

        .file-message a:hover {
            text-decoration: underline;
        }

        .file-icon {
            margin-right: 8px;
            font-size: 18px;
        }

        /* 历史记录面板样式 */
        .history-panel {
            position: fixed;
            top: 0;
            left: 0;
            width: 300px;
            height: 100%;
            background-color: white;
            box-shadow: 2px 0 10px rgba(0,0,0,0.1);
            z-index: 1000;
            transform: translateX(-100%);
            transition: transform 0.3s ease;
            display: flex;
            flex-direction: column;
        }

        .history-panel.active {
            transform: translateX(0);
        }

        .history-header {
            padding: 15px;
            border-bottom: 1px solid #eee;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .history-list {
            flex: 1;
            overflow-y: auto;
            padding: 10px;
        }

        .history-item {
            padding: 10px;
            margin-bottom: 8px;
            border-radius: 4px;
            background-color: #f9f9f9;
            cursor: pointer;
            transition: background-color 0.2s;
        }

        .history-item:hover {
            background-color: #e3f2fd;
        }

        .history-item-time {
            font-size: 12px;
            color: #666;
        }

        .close-history {
            background: none;
            border: none;
            font-size: 20px;
            cursor: pointer;
            color: #666;
        }

        .history-btn {
            padding: 6px 12px;
            background-color: #f0f0f0;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            margin-left: 10px;
        }


    </style>
</head>
<body>
    <!-- 认证界面 (登录/注册) -->
    <div id="auth-page" class="auth-container">
        <h2 class="auth-title" id="auth-title">登录</h2>
        <form id="auth-form" class="auth-form">
            <div id="username-group" class="form-group">
                <label for="username">用户名</label>
                <input type="text" id="username" name="username" required>
            </div>
            <div id="email-group" class="form-group hidden">
                <label for="email">电子邮箱</label>
                <input type="email" id="email" name="email">
            </div>
            <div class="form-group">
                <label for="password">密码</label>
                <input type="password" id="password" name="password" required>
            </div>
            <button type="submit" id="auth-submit">登录</button>
        </form>
        <div class="auth-switch">
            <span id="auth-switch-text">没有账号？</span>
            <a id="auth-switch-btn">注册</a>
        </div>
    </div>

    <!-- 主应用界面 (登录后显示) -->
    <div id="app-container" class="container hidden">
        <!-- 侧边栏 -->
        <div class="sidebar">
            <div class="brand">AI对话系统</div>

            <div id="user-info" class="user-info">
                <div class="user-avatar" id="user-avatar">U</div>
                <div id="username-display">用户名</div>
            </div>

            <div class="nav-menu">
                <div class="nav-item active" data-page="chat">对话</div>
                <div class="nav-item" data-page="roles">角色管理</div>
                <div class="nav-item" data-page="settings">设置</div>
            </div>

            <button id="logout-btn" class="logout-btn">退出登录</button>
        </div>

        <!-- 主内容区 -->
        <div class="main-content">
            <div class="global-controls">
        <button class="nav-btn" onclick="switchPage('chat-page')">对话模式</button>
        <button class="nav-btn" onclick="switchPage('roles-page')">角色管理</button>
        <button class="nav-btn" onclick="switchPage('settings-page')">系统设置</button>
    </div>

            <!-- 对话页面 -->
            <div id="chat-page" class="page">
            <div class="chat-container">
                <div class="chat-header">
                    <h3>新对话</h3>
                    <select id="role-select">
                        <option value="">选择角色...</option>
                        <!-- 角色选项将通过JS动态添加 -->
                    </select>
                    <button id="history-btn" class="history-btn" onclick="toggleHistoryPanel()">历史记录</button>
                </div>

                 <div id="history-panel" class="history-panel">
            <script>
                function toggleHistoryPanel() {
                    const panel = document.getElementById('history-panel');
                    panel.classList.toggle('active');
                }

                function loadHistory() {
                    fetch('/api/chat/history')
                        .then(response => response.json())
                        .then(data => {
                            const historyList = document.getElementById('history-list');
                            historyList.innerHTML = data.map(item => `
                                <div class="history-item" onclick="loadConversation('${item.id}')">
                                    <div>${item.title}</div>
                                    <div class="history-item-time">${new Date(item.timestamp).toLocaleString()}</div>
                                </div>
                            `).join('');
                        });
                }

                function loadConversation(userId) {  // 参数名改为userId更清晰
                fetch(`/api/chat/history/${userId}/messages`)  // 修改端点格式
                    .then(response => response.json())
                    .then(data => {
                        const messagesContainer = document.getElementById('chat-messages');
                        messagesContainer.innerHTML = data.messages.map(msg =>
                            `<div class="message ${msg.role}">
                                <div class="message-content">${msg.content}</div>
                                <div class="message-time">${new Date(msg.created_at).toLocaleString()}</div>
                            </div>`
                        ).join('');
                        toggleHistoryPanel();
                    });
            }

                document.addEventListener('DOMContentLoaded', loadHistory);
            </script>
                    <div class="history-header">
                        <h4>历史对话</h4>
                        <button id="close-history" class="close-history">×</button>
                    </div>
                    <div id="history-list" class="history-list">
                        <!-- 历史记录将通过JS动态添加 -->
                    </div>
                </div>

                <div class="chat-messages" id="chat-messages">
                    <!-- 消息将通过JS动态添加 -->
                </div>

                <div class="chat-input">
                    <input type="text" id="message-input" placeholder="输入消息...">
                    <button id="send-btn">发送</button>
                </div>
            </div>
        </div>


            <!-- 角色管理页面 -->
            <div id="roles-page" class="page hidden">
                <div class="role-management">
                    <h2>角色管理</h2>
                    <button id="add-role-btn" class="add-role-btn">添加新角色</button>

                    <div class="role-list" id="role-list">
                        <!-- 角色卡片将通过JS动态添加 -->
                    </div>
                </div>
            </div>

            <!-- 设置页面 -->
            <div id="settings-page" class="page hidden">
                <div class="settings-container">
                    <h2>设置</h2>

                    <form id="settings-form" class="settings-form">
                        <div class="form-group">
                            <label for="max-tokens">最大Token数</label>
                            <input type="number" id="max-tokens" name="max_tokens" min="100" max="4000" step="100">
                        </div>

                        <div class="form-group">
                            <label for="temperature">温度 (0-2)</label>
                            <input type="number" id="temperature" name="temperature" min="0" max="2" step="0.1">
                        </div>

                        <div class="form-group">
                            <label for="top-p">Top P (0-1)</label>
                            <input type="number" id="top-p" name="top_p" min="0" max="1" step="0.1">
                        </div>

                        <div class="form-group">
                            <label for="presence-penalty">存在惩罚 (-2-2)</label>
                            <input type="number" id="presence-penalty" name="presence_penalty" min="-2" max="2" step="0.1">
                        </div>

                        <div class="form-group">
                            <label for="frequency-penalty">频率惩罚 (-2-2)</label>
                            <input type="number" id="frequency-penalty" name="frequency_penalty" min="-2" max="2" step="0.1">
                        </div>

                        <button type="submit">保存设置</button>
                    </form>
                </div>
            </div>

        </div>
    </div>

    <!-- 添加/编辑角色模态框 -->
    <div id="role-modal" class="hidden" style="position: fixed; top: 0; left: 0; width: 100%; height: 100%; background-color: rgba(0,0,0,0.5); display: flex; justify-content: center; align-items: center;">
        <div style="background-color: white; padding: 20px; border-radius: 10px; width: 500px;">
            <h2 id="role-modal-title">添加新角色</h2>
            <form id="role-form">
                <input type="hidden" id="edit-role-id">
                <div class="form-group">
                    <label for="role-name">角色名称</label>
                    <input type="text" id="role-name" required>
                </div>
                <div class="form-group">
                    <label for="role-description">角色描述</label>
                    <input type="text" id="role-description">
                </div>
                <div class="form-group">
                    <label for="system-prompt">系统提示</label>
                    <textarea id="system-prompt" rows="5" style="width: 100%;" required></textarea>
                </div>
                <div style="display: flex; justify-content: space-between; margin-top: 20px;">
                    <button type="button" id="cancel-role-btn" style="padding: 10px 20px; background-color: #e74c3c; color: white; border: none; border-radius: 5px;">取消</button>
                    <button type="submit" style="padding: 10px 20px; background-color: #2ecc71; color: white; border: none; border-radius: 5px;">保存</button>
                </div>
            </form>
        </div>
    </div>

    <script>
        // 全局变量
        let currentUser = null;
        let currentConversationId = null;
        let roles = [];
        let settings = {
            max_tokens: 2000,
            temperature: 0.7,
            top_p: 1.0,
            presence_penalty: 0.0,
            frequency_penalty: 0.0
        };
        let conversations = JSON.parse(localStorage.getItem('chatConversations')) || [];
        // DOM元素
        const authPage = document.getElementById('auth-page');
        const appContainer = document.getElementById('app-container');
        const authTitle = document.getElementById('auth-title');
        const authForm = document.getElementById('auth-form');
        const authSubmit = document.getElementById('auth-submit');
        const authSwitchText = document.getElementById('auth-switch-text');
        const authSwitchBtn = document.getElementById('auth-switch-btn');
        const usernameGroup = document.getElementById('username-group');
        const emailGroup = document.getElementById('email-group');
        const userInfo = document.getElementById('user-info');
        const usernameDisplay = document.getElementById('username-display');
        const userAvatar = document.getElementById('user-avatar');
        const logoutBtn = document.getElementById('logout-btn');
        const navItems = document.querySelectorAll('.nav-item');
        const pages = document.querySelectorAll('.page');
        const chatMessages = document.getElementById('chat-messages');
        const messageInput = document.getElementById('message-input');
        const sendBtn = document.getElementById('send-btn');
        const roleSelect = document.getElementById('role-select');
        const roleList = document.getElementById('role-list');
        const addRoleBtn = document.getElementById('add-role-btn');
        const roleModal = document.getElementById('role-modal');
        const roleModalTitle = document.getElementById('role-modal-title');
        const roleForm = document.getElementById('role-form');
        const cancelRoleBtn = document.getElementById('cancel-role-btn');
        const settingsForm = document.getElementById('settings-form');

        // 初始化
        document.addEventListener('DOMContentLoaded', () => {
            // 检查登录状态
            checkAuthStatus();

            // 绑定事件
            bindEvents();
             const uploadInput = document.getElementById('file-upload');
            if (!uploadInput) {
                console.error('错误：找不到文件上传输入框');
                return;
            }

            console.log('文件上传组件初始化成功');

             document.addEventListener('DOMContentLoaded', function() {
                const fileUpload = document.getElementById('file-upload');
                fileUpload.addEventListener('change', function(e) {
                console.log('文件选择已触发'); // 调试点2
        });})

        });

        // 检查认证状态
        async function checkAuthStatus() {
            try {
                const response = await fetch('/api/check_auth', {
                    credentials: 'include'
                });

                if (response.ok) {
                    const data = await response.json();
                    if (data.authenticated) {
                        currentUser = { id: data.user_id };
                        loadUserData();
                        showApp();
                    } else {
                        showAuth();
                    }
                } else {
                    showAuth();
                }
            } catch (error) {
                console.error('检查认证状态失败:', error);
                showAuth();
            }
        }

        // 绑定事件
        function bindEvents() {
            // 认证表单切换
            authSwitchBtn.addEventListener('click', toggleAuthMode);

            // 认证表单提交
            authForm.addEventListener('submit', handleAuthSubmit);

            // 导航菜单点击
            navItems.forEach(item => {
                item.addEventListener('click', () => {
                    const page = item.getAttribute('data-page');
                    showPage(page);

                    // 更新活动状态
                    navItems.forEach(navItem => navItem.classList.remove('active'));
                    item.classList.add('active');
                });
            });

            // 退出登录
            logoutBtn.addEventListener('click', logout);

            // 发送消息
            sendBtn.addEventListener('click', sendMessage);
            messageInput.addEventListener('keypress', (e) => {
                if (e.key === 'Enter') {
                    sendMessage();
                }
            });

            // 角色选择
            roleSelect.addEventListener('change', startNewConversation);

            // 角色管理
            addRoleBtn.addEventListener('click', () => showRoleModal());
            cancelRoleBtn.addEventListener('click', () => hideRoleModal());
            roleForm.addEventListener('submit', handleRoleSubmit);

            // 设置表单
            settingsForm.addEventListener('submit', saveSettings);
        }

        // 切换登录/注册模式
        function toggleAuthMode() {
            const isLogin = authTitle.textContent === '登录';

            if (isLogin) {
                authTitle.textContent = '注册';
                authSubmit.textContent = '注册';
                authSwitchText.textContent = '已有账号？';
                authSwitchBtn.textContent = '登录';
                emailGroup.classList.remove('hidden');
            } else {
                authTitle.textContent = '登录';
                authSubmit.textContent = '登录';
                authSwitchText.textContent = '没有账号？';
                authSwitchBtn.textContent = '注册';
                emailGroup.classList.add('hidden');
            }
        }

        // 处理认证表单提交
        async function handleAuthSubmit(e) {
            e.preventDefault();

            const isLogin = authTitle.textContent === '登录';
            const username = document.getElementById('username').value;
            const password = document.getElementById('password').value;
            const email = isLogin ? null : document.getElementById('email').value;

            const endpoint = isLogin ? '/api/login' : '/api/register';
            const data = isLogin ? { username, password } : { username, email, password };

            try {
                const response = await fetch(endpoint, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    credentials: 'include',
                    body: JSON.stringify(data)
                });

                if (response.ok) {
                    const result = await response.json();

                    if (isLogin) {
                        currentUser = { id: result.user_id, username };
                        loadUserData();
                        showApp();
                    } else {
                        toggleAuthMode();
                        alert('注册成功，请登录');
                    }
                } else {
                    const error = await response.json();
                    alert(error.error || '操作失败');
                }
            } catch (error) {
                console.error('认证错误:', error);
                alert('发生错误，请重试');
            }
        }

        // 加载用户数据
        async function loadUserData() {
            try {
                // 加载用户信息
                const userResponse = await fetch(`/api/user/${currentUser.id}`, {
                    credentials: 'include'
                });

                if (userResponse.ok) {
                    const userData = await userResponse.json();
                    currentUser = userData;
                    usernameDisplay.textContent = userData.username;
                    userAvatar.textContent = userData.username.charAt(0).toUpperCase();
                }

                // 加载角色
                const rolesResponse = await fetch('/api/get_roles', {
                    credentials: 'include'
                });

                if (rolesResponse.ok) {
                    roles = (await rolesResponse.json()).roles
                    updateRoleSelect();
                    updateRoleList();
                }

                // 加载设置
                const settingsResponse = await fetch('/api/get_settings', {
                    credentials: 'include'
                });

                if (settingsResponse.ok) {
                    settings = await settingsResponse.json();
                    updateSettingsForm();
                }
            } catch (error) {
                console.error('加载用户数据失败:', error);
            }
        }

        // 更新角色选择下拉框
        function updateRoleSelect() {
            roleSelect.innerHTML = '<option value="">选择角色...</option>';

            roles.forEach(role => {
                const option = document.createElement('option');
                option.value = role.id;
                option.textContent = role.name;
                roleSelect.appendChild(option);
            });
        }

        // 更新角色列表
        function updateRoleList() {
            roleList.innerHTML = '';

            roles.forEach(role => {
                const card = document.createElement('div');
                card.className = 'role-card';
                card.innerHTML = `
                    <h3>${role.name}</h3>
                    <p>${role.description || '暂无描述'}</p>
                    <div class="role-actions">
                        <button class="edit-btn" data-id="${role.id}">编辑</button>
                        <button class="delete-btn" data-id="${role.id}">删除</button>
                    </div>
                `;
                roleList.appendChild(card);
            });

            // 绑定编辑和删除按钮事件
            document.querySelectorAll('.edit-btn').forEach(btn => {
                btn.addEventListener('click', () => editRole(btn.getAttribute('data-id')));
            });

            document.querySelectorAll('.delete-btn').forEach(btn => {
                btn.addEventListener('click', () => deleteRole(btn.getAttribute('data-id')));
            });
        }

        // 开始新对话
        async function startNewConversation() {
            const roleId = roleSelect.value;
            if (!roleId) return;

            try {
                const response = await fetch('/api/start_conversation', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    credentials: 'include',
                    body: JSON.stringify({ role_id: roleId })
                });

                if (response.ok) {
                    const result = await response.json();
                    currentConversationId = result.conversation_id;

                    // 清空消息区域
                    chatMessages.innerHTML = '';

                    // 加载对话历史
                    await loadConversationHistory();
                }
            } catch (error) {
                console.error('开始新对话失败:', error);
            }
        }

        // 加载对话历史
        async function loadConversationHistory() {
            if (!currentConversationId) return;

            try {
                const response = await fetch(`/api/get_conversation?conversation_id=${currentConversationId}`, {
                    credentials: 'include'
                });

                if (response.ok) {
                    const data = await response.json();

                    // 显示对话历史
                    chatMessages.innerHTML = '';
                    data.conversation.messages.forEach(msg => {
                        addMessageToChat(msg.role, msg.content);
                    });
                }
            } catch (error) {
                console.error('加载对话历史失败:', error);
            }
        }
        
        // 加载特定对话
        async function loadConversationMessage(conversationId) {
            currentConversationId = conversationId;
            await loadConversationHistory();
            toggleHistoryPanel();
        }

        // 发送消息
        async function sendMessage() {
            const message = messageInput.value.trim();
            const roleId = document.getElementById('role-select').value;
            if (!message) return;

            // 添加用户消息到聊天界面
            addMessageToChat('user', message);
            messageInput.value = '';

            try {
                const response = await fetch('/api/send_message', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    credentials: 'include',
                    body: JSON.stringify({
                        message:message,
                        conversation_id: currentConversationId,
                        role_id:roleId
                    })
                });

                if (response.ok) {
                    const result = await response.json();
                    addMessageToChat('assistant', result.response || result.message);
                } else {
                    const error = await response.json();
                    addMessageToChat('system', `错误: ${error.error}`);
                }
            } catch (error) {
                console.error('发送消息失败:', error);
                addMessageToChat('system', '发送消息时发生错误');
            }
            document.getElementById('message-input').value = ''; // 清空输入框
        }

        // 添加消息到聊天界面
        function addMessageToChat(role, content) {
            const chatBox = document.getElementById('chat-box');
            const messageDiv = document.createElement('div');
            messageDiv.className = `message ${role}`;
            messageDiv.textContent = content;
            chatMessages.appendChild(messageDiv);
            chatMessages.scrollTop = chatMessages.scrollHeight;
        }

        // 显示角色模态框
        function showRoleModal(role = null) {
            if (role) {
                // 编辑模式
                roleModalTitle.textContent = '编辑角色';
                document.getElementById('edit-role-id').value = role.id;
                document.getElementById('role-name').value = role.name;
                document.getElementById('role-description').value = role.description || '';
                document.getElementById('system-prompt').value = role.system_prompt;
            } else {
                // 添加模式
                roleModalTitle.textContent = '添加新角色';
                document.getElementById('edit-role-id').value = '';
                document.getElementById('role-name').value = '';
                document.getElementById('role-description').value = '';
                document.getElementById('system-prompt').value = '';
            }

            roleModal.classList.remove('hidden');
        }

        // 隐藏角色模态框
        function hideRoleModal() {
            roleModal.classList.add('hidden');
        }

        // 处理角色表单提交
        async function handleRoleSubmit(e) {
            e.preventDefault();

            const roleId = document.getElementById('edit-role-id').value;
            const name = document.getElementById('role-name').value;
            const description = document.getElementById('role-description').value;
            const systemPrompt = document.getElementById('system-prompt').value;

            const endpoint = roleId ? '/api/update_role' : '/api/create_role';
            const method = roleId ? 'PUT' : 'POST';

            try {
                const response = await fetch(endpoint, {
                    method,
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    credentials: 'include',
                    body: JSON.stringify({
                        id: roleId || undefined,
                        name,
                        description,
                        system_prompt: systemPrompt
                    })
                });

                if (response.ok) {
                    const result = await response.json();
                    hideRoleModal();
                    loadUserData(); // 重新加载角色数据
                } else {
                    const error = await response.json();
                    alert(error.error || '操作失败');
                }
            } catch (error) {
                console.error('保存角色失败:', error);
                alert('保存角色时发生错误');
            }
        }

        // 编辑角色
        function editRole(roleId) {
            const role = roles.find(r => r.id === roleId);
            if (role) {
                showRoleModal(role);
            }
        }

        // 删除角色
        async function deleteRole(roleId) {
            if (!confirm('确定要删除这个角色吗？')) return;

            try {
                const response = await fetch(`/api/delete_role/${roleId}`, {
                    method: 'DELETE',
                    credentials: 'include'
                });

                if (response.ok) {
                    loadUserData(); // 重新加载角色数据
                } else {
                    const error = await response.json();
                    alert(error.error || '删除失败');
                }
            } catch (error) {
                console.error('删除角色失败:', error);
                alert('删除角色时发生错误');
            }
        }

        // 更新设置表单
        function updateSettingsForm() {
            document.getElementById('max-tokens').value = settings.max_tokens;
            document.getElementById('temperature').value = settings.temperature;
            document.getElementById('top-p').value = settings.top_p;
            document.getElementById('presence-penalty').value = settings.presence_penalty;
            document.getElementById('frequency-penalty').value = settings.frequency_penalty;
        }

        // 保存设置
        async function saveSettings(e) {
            e.preventDefault();

            const formData = {
                max_tokens: parseInt(document.getElementById('max-tokens').value),
                temperature: parseFloat(document.getElementById('temperature').value),
                top_p: parseFloat(document.getElementById('top-p').value),
                presence_penalty: parseFloat(document.getElementById('presence-penalty').value),
                frequency_penalty: parseFloat(document.getElementById('frequency-penalty').value)
            };

            try {
                const response = await fetch('/api/update_settings', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    credentials: 'include',
                    body: JSON.stringify(formData)
                });

                if (response.ok) {
                    settings = formData;
                    alert('设置已保存');
                } else {
                    const error = await response.json();
                    alert(error.error || '保存设置失败');
                }
            } catch (error) {
                console.error('保存设置失败:', error);
                alert('保存设置时发生错误');
            }
        }

        // 显示页面
        function showPage(pageId) {
            pages.forEach(page => {
                if (page.id === `${pageId}-page`) {
                    page.classList.remove('hidden');
                } else {
                    page.classList.add('hidden');
                }
            });
        }

        // 显示应用界面
        function showApp() {
            authPage.classList.add('hidden');
            appContainer.classList.remove('hidden');
            showPage('chat');
        }

        // 显示认证界面
        function showAuth() {
            authPage.classList.remove('hidden');
            appContainer.classList.add('hidden');
        }

        // 退出登录
        async function logout() {
            try {
                await fetch('/api/logout', {
                    method: 'POST',
                    credentials: 'include'
                });

                currentUser = null;
                window.location.href = '/';
            } catch (error) {
                console.error('退出登录失败:', error);
            }
        }

         //在您的JavaScript文件中添加
        document.getElementById('iot-route-btn').addEventListener('click', function() {
            window.location.href = '/api/iot';
        });

        // 统一路由处理
        // function handleRouteChange() {
        //   const path = window.location.pathname;
        //   // 根据 path 执行对应的页面更新逻辑
        //   console.log('Current path:', path);
        // }
        //
        // // 监听历史记录变化
        // window.addEventListener('popstate', handleRouteChange);
        //
        // // 统一路由跳转方法
        // function navigateTo(path) {
        //   history.pushState({}, '', path);
        //   handleRouteChange(); // 立即处理新路由
        // }
        //
        // // IoT 按钮点击
        // document.querySelector('.iot-btn').addEventListener('click', () => {
        //   if(confirm('切换至 IoT 控制台？未保存的更改可能会丢失')) {
        //     navigateTo('/api/iot');
        //   }
        // });

        // 页面切换函数
        function switchPage(pageId) {
          // 隐藏所有页面
          document.querySelectorAll('.page').forEach(page => {
            page.classList.add('hidden');
          });

          // 显示目标页面
          const targetPage = document.getElementById(pageId);
          if (targetPage) {
            targetPage.classList.remove('hidden');
          }

          // 更新按钮激活状态
          document.querySelectorAll('.nav-btn').forEach(btn => {
            btn.classList.remove('active');
          });
          document.querySelector(`[onclick*="${pageId}"]`).classList.add('active');
        }

        // 初始化默认页面
        window.addEventListener('DOMContentLoaded', () => {
          switchPage('chat-page'); // 默认打开对话页面
        });

        // 可选：处理浏览器前进/后退
        window.addEventListener('popstate', () => {
          const path = window.location.pathname;
          if (path.includes('settings')) {
            switchPage('settings-page');
          } else if (path.includes('roles')) {
            switchPage('roles-page');
          } else {
            switchPage('chat-page');
          }
        });

        // 文件上传处理
        const fileUpload = document.getElementById('file-upload');
        if (fileUpload) {
            fileUpload.addEventListener('change', function(e) {
            const fileInput = e.target;
            const fileNameDisplay = document.getElementById('file-name');

            if (fileInput.files.length > 0) {
                const file = fileInput.files[0];
                console.log('Selected file:', file.name);

                // 显示文件名
                fileNameDisplay.textContent = file.name;
                fileNameDisplay.style.color = '#333';
                fileNameDisplay.style.display = 'inline';

                // 触发文件上传逻辑
                handleFileUpload(file);
            } else {
                fileNameDisplay.textContent = '未选择文件';
                fileNameDisplay.style.color = '#666';
                fileNameDisplay.style.display = 'inline';
            }
        });
        }

        function handleFileUpload(file) {
    try {
        const formData = new FormData();
        formData.append('file', file);

        // 添加上传取消功能
        const controller = new AbortController();
        const timeoutId = setTimeout(() => controller.abort(), 30000);

        fetch('/api/upload', {
            method: 'POST',
            body: formData,
            signal: controller.signal
        })
        .then(response => {
            clearTimeout(timeoutId);
            if (!response.ok) {
                // 获取详细错误信息
                return response.json().then(err => Promise.reject(err));
            }
            return response.json();
        })
        .then(data => {
            console.log('上传响应数据:', data); // 调试输出
            if (!data.url) throw new Error('服务器返回数据异常');
            uploadStatus.innerHTML = `<div class='file-upload-success'>文件上传成功: <a href="${data.url}" target="_blank">${file.name}</a></div>`;
        })
        .catch(error => {
            console.error('完整错误信息:', error);
            uploadStatus.innerHTML = `上传失败: ${file.name} <button onclick="retryUpload('${file.name}')">重试</button>`;
                });
            } catch (error) {
                console.error('上传处理异常:', error);
            }
        }

        function retryUpload(fileName) {
            const fileInput = document.getElementById('file-upload');
            if (fileInput.files.length > 0 && fileInput.files[0].name === fileName) {
                handleFileUpload(fileInput.files[0]);
            }
        }

        // 修改发送消息函数
        document.getElementById('send-btn').addEventListener('click', async function() {
            const messageInput = document.getElementById('message-input');
            const fileInput = document.getElementById('file-upload');
            const roleSelect = document.getElementById('role-select');

            const message = messageInput.value.trim();
            const file = fileInput.files[0];
            const role = roleSelect.value;

            if (!message && !file) return;

            if (!currentConversationId) {
                createNewConversation();
            }
            // 显示用户消息
            displayMessage('user', message, file);

            // 如果是文件，读取内容
            let fileContent = null;
            if (file) {
                try {
                    fileContent = await readFileAsText(file);
                } catch (error) {
                    console.error('读取文件失败:', error);
                    return;
                }
            }

            // 发送到服务器
            try {
                const formData = new FormData();
                if (message) formData.append('message', message);
                if (file) formData.append('file', file);
                if (role) formData.append('role', role);

                const response = await fetch('/api/chat', {
                    method: 'POST',
                    body: formData
                });

                const result = await response.json();
                displayMessage('assistant', result.reply);

            } catch (error) {
                console.error('发送消息失败:', error);
            }

            // 清空输入
            messageInput.value = '';
            fileInput.value = '';
            document.getElementById('file-name').textContent = '未选择文件';
        });

        // 辅助函数：读取文件为文本
        function readFileAsText(file) {
            return new Promise((resolve, reject) => {
                const reader = new FileReader();
                reader.onload = event => resolve(event.target.result);
                reader.onerror = error => reject(error);
                reader.readAsText(file);
            });
        }

        // 显示消息函数（修改版）
        // function displayMessage(sender, text, file = null) {
        //     const messagesContainer = document.getElementById('chat-messages');
        //     const messageElement = document.createElement('div');
        //     messageElement.className = `message ${sender}`;
        //
        //     if (file) {
        //         const fileElement = document.createElement('div');
        //         fileElement.className = 'file-message';
        //
        //         const fileType = file.name.split('.').pop().toLowerCase();
        //         const fileIcon = getFileIcon(fileType);
        //
        //         fileElement.innerHTML = `
        //             <a href="#" class="download-link" data-filename="${file.name}">
        //                 <span class="file-icon">${fileIcon}</span>
        //                 ${file.name}
        //             </a>
        //         `;
        //         messageElement.appendChild(fileElement);
        //     }

        //     if (text) {
        //         const textElement = document.createElement('div');
        //         textElement.className = 'text-message';
        //         textElement.textContent = text;
        //         messageElement.appendChild(textElement);
        //     }
        //
        //     messagesContainer.appendChild(messageElement);
        //     messagesContainer.scrollTop = messagesContainer.scrollHeight;
        // }

        // 获取文件类型图标
        function getFileIcon(fileType) {
            const icons = {
                txt: '📄',
                csv: '📊',
                json: '🔣',
                log: '📋',
                xml: '📑',
                // 可以添加更多文件类型图标
            };
            return icons[fileType] || '📁';
        }

        function loadHistory() {
            fetch('/api/chat/history')
                .then(response => response.json())
                .then(data => {
                    const historyList = document.getElementById('history-list');
                    historyList.innerHTML = '';

                    data.forEach(conv => {
                        const item = document.createElement('div');
                        item.className = 'history-item';
                        item.innerHTML = `
                            <div>${conv.messages[0]?.text?.substring(0, 30) || '新对话'}...</div>
                            <div class="history-item-time">${new Date(conv.timestamp).toLocaleString()}</div>
                        `;

                        item.addEventListener('click', () => {
                            loadConversationMessage(conv.id);
                            document.getElementById('history-panel').classList.remove('active');
                        });

                        historyList.appendChild(item);
                    });
                })
                .catch(error => console.error('加载历史记录失败:', error));
        }

        // 加载特定对话
        function loadConversation(conversationId) {
            fetch(`/api/chat/history/${conversationId}/messages`)
                .then(response => response.json())
                .then(data => {
                    const messagesContainer = document.getElementById('chat-messages');
                    messagesContainer.innerHTML = data.messages.map(msg => 
                        `<div class="message ${msg.role}">
                            <div class="message-content">${msg.content}</div>
                            <div class="message-time">${new Date(msg.created_at).toLocaleString()}</div>
                        </div>`
                    ).join('');
                    toggleHistoryPanel();
                })
                .catch(error => console.error('加载对话失败:', error));
        }

        // 创建新对话
        function createNewConversation() {
            const newConversation = {
                id: Date.now().toString(),
                timestamp: new Date().toISOString(),
                role: document.getElementById('role-select').value,
                messages: []
            };

            currentConversationId = newConversation.id;
            conversations.unshift(newConversation);
            saveConversations();
            loadHistory();

            // 清空消息显示
            document.getElementById('chat-messages').innerHTML = '';
        }

        // 保存消息到当前对话
        function saveMessage(sender, text, file = null) {
            if (!currentConversationId) {
                createNewConversation();
            }

            const conversation = conversations.find(c => c.id === currentConversationId);
            if (conversation) {
                conversation.messages.push({
                    sender,
                    text,
                    file: file ? { name: file.name, type: file.type } : null,
                    timestamp: new Date().toISOString()
                });

                saveConversations();
            }
        }

        // 保存所有对话到localStorage
        function saveConversations() {
            localStorage.setItem('chatConversations', JSON.stringify(conversations));
            loadHistory();
        }

        // 修改后的displayMessage函数
        function displayMessage(sender, text, file = null) {
            const messagesContainer = document.getElementById('chat-messages');
            const messageElement = document.createElement('div');
            messageElement.className = `message ${sender}`;

            if (file) {
                const fileElement = document.createElement('div');
                fileElement.className = 'file-message';
                const fileType = file.name.split('.').pop().toLowerCase();
                const fileIcon = getFileIcon(fileType);

                fileElement.innerHTML = `
                    <a href="#" class="download-link" data-filename="${file.name}">
                        <span class="file-icon">${fileIcon}</span>
                        ${file.name}
                    </a>
                `;
                messageElement.appendChild(fileElement);
            }

            if (text) {
                const textElement = document.createElement('div');
                textElement.className = 'text-message';
                textElement.textContent = text;
                messageElement.appendChild(textElement);
            }

            // 添加时间戳
            const timeElement = document.createElement('div');
            timeElement.className = 'message-time';
            timeElement.textContent = new Date().toLocaleTimeString();
            messageElement.appendChild(timeElement);

            messagesContainer.appendChild(messageElement);
            messagesContainer.scrollTop = messagesContainer.scrollHeight;

            // 保存消息
            saveMessage(sender, text, file);
        }

        // 初始化历史记录按钮事件
        document.getElementById('history-btn').addEventListener('click', function() {
            document.getElementById('history-panel').classList.toggle('active');
        });

        document.getElementById('close-history').addEventListener('click', function() {
            document.getElementById('history-panel').classList.remove('active');
        });

        // 页面加载时初始化
        document.addEventListener('DOMContentLoaded', function() {
            loadHistory();

            // 如果没有任何对话，创建一个新的
            if (conversations.length === 0) {
                createNewConversation();
            } else {
                // 默认加载最新的对话
                loadConversation(conversations[0].id);
            }
        });
    </script>
</body>
</html>
